<?php
class BaseModel{
	const MODEL_SURFIX = "Model";
	protected $_error;
	protected $_message;
	protected $_hasError;
	private $_context;
	/**
	 * Array of Error.
	 * @var array
	 */
	private $_errors;
	/**
	 * Entity Object.
	 * @var BaseEntity
	 */
	private $_entity;
	
	public function __construct(){
		$this->_hasError = false;
	}
	/**
	 * Validate input entity and return output Entity.
	 * @param array $entity
	 */
	public function validate1($entity){
		return $entity;
	}
	public function getByIDT($id){
		return $this->_entity->getByIDT($id);
	}
	public function getByID($id){
		return $this->_entity->getByID($id);
	}
	public function getByID1($id){
		return $this->_entity->getByID1($id);
	}
	public function addOrUpdate(array $entity){
		foreach ($this->getEntity()->unsetCols as $value) {
			$key = ":" . $value;
			if(isset($entity[$key]))
				unset($entity[$key]);
		}
		$result = DBHelper::FAIL;
		$entity = $this->validate1($entity);
		if($this->getEntity()->isExist1($entity)){
			$result = $this->getEntity()->update1($entity);
		}
		else{
			$result = $this->getEntity()->insertSimple1($entity);
		}
		if($result == DBHelper::SUCCESS){
			return $this->getEntity()->getByIDJoin1($entity);
		}
		return null;
	}
	
	public function insertOrUpdate(array $entity){
		$result = DBHelper::FAIL;
		if($this->_entity->isExist($entity)){
			$result = $this->_entity->update($entity);
		}
		else {
			$result = $this->_entity->insert($entity);
		}
		if($result == DBHelper::SUCCESS){
			return $this->_entity->getByIDT($entity);
		}
		$this->setErrors($this->_entity->getErrorsMessage());
		return null;
	}
	public function setContext($context){
		$this->_context = $context;
		$this->_entity = EntityFactory::instance($context);
	}
	public function setEntity($entity){
		if(isset($entity)){
			$this->_entity = $entity;
			$this->_context = $this->_entity->getClass();
		}
	}
	/**
	 * Return Model Class ...
	 * @return string
	 */
	public function getClass(){
		return get_class($this);
	}
	public function hasError(){
		return $this->_hasError;
	}
	public function getError(){
		return $this->_error;
	}
	public function getMessage(){
		return $this->_message;
	}
	public function getEntity(){
		return $this->_entity;
	}
	/**
	 * @return the $_errors
	 */
	public function getErrors() {
		return $this->_errors;
	}

	/**
	 * @param array $_errors
	 */
	public function setErrors($_errors) {
		$this->_errors = $_errors;
	}
	public function addErrors($error) {
		array_push($this->_errors, $error);
	}
}